﻿package 
{
	import flash.utils.Timer;
	import flash.display.Stage;
	import flash.events.KeyboardEvent;
	import flash.events.Event;
	import flash.events.TimerEvent;

	public class GameManager
	{
		private var mainStage:Stage;
		private var battleField:BattleField = new BattleField();
		private var player:Player = new Player(25,25);

		var leftArrow:Boolean = false;
		var rightArrow:Boolean = false;
		var upArrow:Boolean = false;
		var downArrow:Boolean = false;
		
		public function GameManager(mainStage:Stage)
		{
			this.mainStage = mainStage;

			this.mainStage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
			this.mainStage.addEventListener(KeyboardEvent.KEY_UP, keyPressedUp);
			this.mainStage.addEventListener(Event.ENTER_FRAME, movePlayer);

			createGame();
		
		}

		public function createGame()
		{
			mainStage.addChild(battleField);
			mainStage.addChild(player.clip);
		}

		private function keyPressedDown(event:KeyboardEvent)
		{
			if (event.keyCode == 37)
			{
				leftArrow = true;
			}
			else if (event.keyCode == 39)
			{
				rightArrow = true;
			}
			else if (event.keyCode == 38)
			{
				upArrow = true;
			}
			else if (event.keyCode == 40)
			{
				downArrow = true;
			}
			else if (event.keyCode == 32)  //SpaceBar
			{
				battleField.placeBomb(player);
			}
		}

		private function keyPressedUp(event:KeyboardEvent)
		{
			if (event.keyCode == 37)
			{
				leftArrow = false;
			}
			else if (event.keyCode == 39)
			{
				rightArrow = false;
			}
			else if (event.keyCode == 38)
			{
				upArrow = false;
			}
			else if (event.keyCode == 40)
			{
				downArrow = false;
			}
		}

		function movePlayer(event:Event)
		{
			var hit:Boolean = false;
			
			if (leftArrow == true) {
				player.clip.x -=  player.getMoveSpeed();
				
				hit = battleField.checkCollisions(player);
				
				if (hit) {
					player.clip.x +=  player.getMoveSpeed();
				}
			}			
			if (rightArrow == true) {
				player.clip.x +=  player.getMoveSpeed();
				
				hit = battleField.checkCollisions(player);
				
				if (hit) {
					player.clip.x -=  player.getMoveSpeed();
				}
			}
			if (upArrow == true) {
				player.clip.y -=  player.getMoveSpeed();
				
				hit = battleField.checkCollisions(player);
				
				if (hit) {
					player.clip.y +=  player.getMoveSpeed();
				}
			}
			if (downArrow == true) {
				player.clip.y +=  player.getMoveSpeed();
				
				hit = battleField.checkCollisions(player);
				
				if (hit) {
					player.clip.y -=  player.getMoveSpeed();
				}
			}
		}
	}
}